package io.renren.modules.api.resolver;

import io.renren.modules.api.annotation.LoginDriver;
import io.renren.modules.api.entity.UserEntity;
import io.renren.modules.api.interceptor.AuthorizationInterceptor;
import io.renren.modules.api.service.UserService;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.SjDriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * Created by WDJ on 2017/12/11.
 */
@Component
public class LoginDriverHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private SjDriverService driverService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SjDriverEntity.class) && parameter.hasParameterAnnotation(LoginDriver.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest request, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(AuthorizationInterceptor.LOGIN_DRIVER_KEY, RequestAttributes.SCOPE_REQUEST);
        if(object == null){
            return null;
        }

        //获取司机信息
        SjDriverEntity driver = driverService.queryObject((Long)object);
        return driver;
    }
}
